package com.hnxxxy.oa.sign.util;

import com.hnxxxy.oa.sign.entity.SignDO;
import com.hnxxxy.oa.sign.entity.WorktimeDO;
import com.hnxxxy.oa.sign.mapper.WorkTimeMapper;
import com.hnxxxy.oa.sign.request.SignRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author 1112
 * 2022/5/12
 */

@Component
public class SignParser {
    @Autowired
    private WorkTimeMapper mapper;

    public SignDO parse(SignRequest request) throws ParseException {
        //构建待返回的DO对象
        SignDO signDO = new SignDO();
        signDO.setUserId(request.getUserId());
        signDO.setRemark(request.getRemark());
        signDO.setTime(request.getTime());
        signDO.setWorkTimeId(request.getWorkTimeId());
        signDO.setCreateTime(SimpleDateFormat.getDateInstance().parse(LocalDate.now().toString()));

        // 查询对应的工作时间安排
        WorktimeDO worktimeDO = mapper.selectById(signDO.getWorkTimeId());
        signDO.setTag(0);
        // 根据工作时间安排对签到/签退时间进行迟到/早退判断
        if (request.getIsSignIn()) {

            if (compareTime(signDO.getTime(), worktimeDO.getOnDutyTime())) {
                signDO.setTag(-1);
            } else {
                signDO.setTag(1);
            }
        } else {
            if (compareTime(worktimeDO.getOffDutyTime(), signDO.getTime())) {
                signDO.setTag(-2);
            } else {
                signDO.setTag(2);
            }
        }

        return signDO;
    }

    /**
     * @param dateA 时间A
     * @param dateB 时间B
     * @return B 是否在 A 之前
     * 比较两个时间,仅精确到分钟
     */
    private boolean compareTime(LocalDateTime dateA, LocalDateTime dateB) {

        return (dateB.getHour() <= dateA.getHour()) &&
                (dateB.getHour() != dateA.getHour() || dateB.getMinute() >= dateA.getMinute());
    }
}
